<?php


namespace app\common\model\user;

use app\common\model\BaseModel;

/**
 * 短信模型
 */
class HwSms extends BaseModel
{
    protected $pk = 'sms_id';
    protected $name = 'sms';

    /**
     * 短信验证码发送
     * $sence 场景，login：登录 apply：供应商申请
     */
    public function send($mobile, $sence = 'login')
    {
        if (empty($mobile)) {
            $this->error = '手机号码不能为空';
            return false;
        }
        if ($sence == 'login') {

        } else if ($sence == 'register') {
            //判断是否已经注册
            $user = (new User)->where('mobile', '=', $mobile)->find();
            if ($user) {
                $this->error = '手机号码已存在';
                return false;
            }
        }
        $code = str_pad(mt_rand(100000, 999999), 6, "0", STR_PAD_BOTH);
        $TEMPLATE_PARAS = "[$code]"; //模板变量，此处以单变量验证码短信为例，请客户自行生成6位验证码，并定义为字符串类型，以杜绝首位0丢失的问题（例如：002569变成了2569）。
        $signature = "碳锁足迹";
        $TEMPLATE_ID = "2bd6bd04d0ad481dada6ca17d95a6e3d";
        $sender = "8821122832149";
        $result = $this->sendSms($mobile, $signature, $TEMPLATE_ID, $TEMPLATE_PARAS, $sender);
        if ($result['code'] == '000000' && $result['result'][0]['status'] == "000000") {
            return $this->save([
                'mobile' => $mobile,
                'code' => $code,
                'sence' => $sence,
                'app_id' => self::$app_id
            ]);
        }
    }

    /**
     * 短信通知发送
     * $sence
     */
    public function sendNotice($mobile, $type = 1, $content = "")
    {
        if (empty($mobile)) {
            $this->error = '手机号码不能为空';
            return false;
        }
        $TEMPLATE_ID = "";
        switch ($type) {
            case '1'://骑手
                $TEMPLATE_ID = "583ab0cd44e94d7f912201b829c8f269";
                break;
            case '2'://加盟商
                $TEMPLATE_ID = "6d02524081f04852a8c6744beb276ba8";
                break;
            case '3'://打包站
                $TEMPLATE_ID = "7c03e9864d3a4fd8813ab7fa1a028a12";
                break;
            case '4'://商户下单给骑手发送短信
                $TEMPLATE_ID = "a3335af568334c79b2af6f8692e55359";
                break;
            case '5'://用户下单给骑手发送短信
                $TEMPLATE_ID = "e7db181cb51b405b9517ea9d4929dab0";
                break;
            case '6'://骑手取消订单给用户发送短信
                $TEMPLATE_ID = "6481603f172542eda3bba355fbb42b6f";
                break;
            case '7'://骑手接订单给用户发送短信
                $TEMPLATE_ID = "1e1e0d45fc8c42e5b9275676f8f5ae16";
                break;
            case '8'://打包站录入给骑手发送短信
                $TEMPLATE_ID = "5b8f6b53799040d5a66babcdecdcbaff";
                break;
            case '9'://给平台发送短信
                $TEMPLATE_ID = "e33b501fe24f44c89c74505e39801fdd";
                break;
            case '10'://转单给骑手发送短信
                $TEMPLATE_ID = "f595558ec5dd4c49b2419a2d20881274";
                break;
            case '11'://下单自动转单发送骑手通知短信
                $TEMPLATE_ID = "f2987e3082934ab388828ee276cb051f";
                break;
            case '12'://骑手申请驳回短信
                $TEMPLATE_ID = "bb10e17421bd408a83d26a94c93b5a8b";
                break;
            case '13'://取消订单给骑手发送短信
                $TEMPLATE_ID = "17243699af894e738b19710e83ae420b";
                break;
        }
        //模板变量，此处以单变量验证码短信为例，请客户自行生成6位验证码，并定义为字符串类型，以杜绝首位0丢失的问题（例如：002569变成了2569）。
        if ($type == 7) {
            $TEMPLATE_PARAS = "['{$content['name']}','{$content['mobile']}']";
        } elseif ($type == 8) {
            $TEMPLATE_PARAS = "[
            '{$content['site_name']}',
            '{$content['weight1']}',
            '{$content['weight2']}',
            '{$content['money1']}',
            '{$content['money2']}',
            '{$content['weight3']}',
            '{$content['money3']}',
            '{$content['rate']}',
            ]";
        } elseif ($type == 10) {
            $TEMPLATE_PARAS = "['{$content}']";
        } elseif ($type == 4 || $type == 5 || $type == 11) {
            $TEMPLATE_PARAS = "[
            '{$content['address']}',
            '{$content['detail']}',
            '{$content['phone']}',
            '{$content['name']}',
            '{$content['time1']}',
            '{$content['time2']}',
            '{$content['time3']}',
            ]";
        } elseif ($type == 12) {
            $TEMPLATE_PARAS = "['{$content['content']}','{$content['phone']}']";
        } elseif ($type == 13) {
            $TEMPLATE_PARAS = "[
            '{$content['address']}',
            '{$content['detail']}',
            '{$content['time1']}',
            '{$content['time2']}',
            '{$content['time3']}',
            '{$content['phone']}',
            '{$content['name']}',
            '{$content['type']}',
            ]";
        } else {
            $TEMPLATE_PARAS = $content ? "[$content]" : '';
        }
        $signature = "碳锁足迹";
        $sender = "8821122832188";
        $result = $this->sendSms($mobile, $signature, $TEMPLATE_ID, $TEMPLATE_PARAS, $sender);
        if ($result['code'] == '000000' && $result['result'][0]['status'] == "000000") {
            return true;
        }
        return false;
    }

    //短信发送
    public function sendSms($mobile, $signature, $TEMPLATE_ID, $TEMPLATE_PARAS, $sender)
    {
        //必填,请参考"开发准备"获取如下数据,替换为实际值
        $url = 'https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1'; //APP接入地址(在控制台"应用管理"页面获取)+接口访问URI
        $APP_KEY = 'AeAF1Aw2o6a2ZcqZD9cgiE0gbyX9'; //APP_Key
        $APP_SECRET = 'vWgKcdjrZ4qEJDoaUn75mvo3tK0w'; //APP_Secret
//        $sender = '1069368924410000990'; //国内短信签名通道号或国际/港澳台短信通道号
        //$TEMPLATE_ID = $TEMPLATE_ID;//'aa1b7b620f424b2fb6d5ee64a5dc3528'; //模板ID

        //条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称
        //国际/港澳台短信不用关注该参数
        //$signature = $signature;//'华为云短信测试'; //签名名称

        //必填,全局号码格式(包含国家码),示例:+86151****6789,多个号码之间用英文逗号分隔
        $receiver = $mobile; //短信接收人号码

        //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
        $statusCallback = '';
//        $code = str_pad(mt_rand(100000, 999999), 6, "0", STR_PAD_BOTH);
        /**
         * 选填,使用无变量模板时请赋空值 $TEMPLATE_PARAS = '';
         * 单变量模板示例:模板内容为"您的验证码是${1}"时,$TEMPLATE_PARAS可填写为'["369751"]'
         * 双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,$TEMPLATE_PARAS可填写为'["3","人民公园正门"]'
         * 模板中的每个变量都必须赋值，且取值不能为空
         * 查看更多模板和变量规范:产品介绍>模板和变量规范
         * @var string $TEMPLATE_PARAS
         */
//        $TEMPLATE_PARAS = "[$code]"; //模板变量，此处以单变量验证码短信为例，请客户自行生成6位验证码，并定义为字符串类型，以杜绝首位0丢失的问题（例如：002569变成了2569）。
        //请求Headers
        $headers = [
            'Content-Type: application/x-www-form-urlencoded',
            'Authorization: WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
            'X-WSSE: ' . $this->buildWsseHeader($APP_KEY, $APP_SECRET)
        ];
        //请求Body
        $data = http_build_query([
            'from' => $sender,
            'to' => $receiver,
            'templateId' => $TEMPLATE_ID,
            'templateParas' => $TEMPLATE_PARAS,
            'statusCallback' => $statusCallback,
            'signature' => $signature //使用国内短信通用模板时,必须填写签名名称
        ]);

        $context_options = [
            'http' => ['method' => 'POST', 'header' => $headers, 'content' => $data, 'ignore_errors' => true],
            'ssl' => ['verify_peer' => false, 'verify_peer_name' => false] //为防止因HTTPS证书认证失败造成API调用失败，需要先忽略证书信任问题
        ];
        $response = file_get_contents($url, false, stream_context_create($context_options));
        $result = json_decode($response, 1);
        return $result;
    }

    /**
     * 构造X-WSSE参数值
     * @param string $appKey
     * @param string $appSecret
     * @return string
     */
    private function buildWsseHeader(string $appKey, string $appSecret)
    {
        date_default_timezone_set('Asia/Shanghai');
        $now = date('Y-m-d\TH:i:s\Z'); //Created
        $nonce = uniqid(); //Nonce
        $base64 = base64_encode(hash('sha256', ($nonce . $now . $appSecret))); //PasswordDigest
        return sprintf("UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"",
            $appKey, $base64, $nonce, $now);
    }

}